"""
报告 API 端点
"""
from uuid import UUID
from urllib.parse import quote
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession

from app.db.session import get_db
from app.crud.record import RecordCRUD
from app.crud.assessment import AssessmentCRUD
from app.schemas.common import ResponseModel
from app.schemas.assessment import AssessmentReport, DimensionScores
from app.core.logger import app_logger
from app.utils.export_utils import ReportExporter


router = APIRouter()


@router.get("/{record_id}", response_model=ResponseModel[AssessmentReport])
async def get_assessment_report(
    record_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    生成完整的评估报告
    """
    # 获取病历
    record = await RecordCRUD.get_by_id(db, record_id)
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="病历不存在"
        )
    
    # 获取最新评估
    assessment = await AssessmentCRUD.get_by_record_id(db, record_id, latest_only=True)
    if not assessment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="该病历暂无评估记录，请先进行评估"
        )
    
    # 构建病历基本信息
    record_info = {
        'id': str(record.id),
        'patient_name': record.patient_name,
        'patient_age': record.patient_age,
        'patient_gender': record.patient_gender,
        'department': record.department,
        'visit_date': record.visit_date.isoformat() if record.visit_date else None,
        'chief_complaint': record.chief_complaint,
        'diagnosis': record.diagnosis,
        'doctor_name': record.doctor_name,
        'created_at': record.created_at.isoformat()
    }
    
    # 构建统计信息
    statistics = {
        'total_issues': len(assessment.issues) if assessment.issues else 0,
        'critical_issues': sum(
            1 for issue in (assessment.issues or [])
            if issue.severity == 'critical'
        ),
        'major_issues': sum(
            1 for issue in (assessment.issues or [])
            if issue.severity == 'major'
        ),
        'minor_issues': sum(
            1 for issue in (assessment.issues or [])
            if issue.severity == 'minor'
        )
    }
    
    # 构建图表数据
    charts_data = {
        'radar_chart': {
            'dimensions': ['完整性', '规范性', '一致性', '准确性'],
            'scores': [
                assessment.completeness_score,
                assessment.standardization_score,
                assessment.consistency_score,
                assessment.accuracy_score
            ],
            'max_score': 100
        },
        'bar_chart': {
            'categories': ['完整性', '规范性', '一致性', '准确性'],
            'values': [
                assessment.completeness_score,
                assessment.standardization_score,
                assessment.consistency_score,
                assessment.accuracy_score
            ]
        },
        'score_gauge': {
            'overall_score': assessment.overall_score,
            'max_score': 100,
            'grade': _get_score_grade(assessment.overall_score)
        },
        'issues_by_type': _group_issues_by_type(assessment.issues or []),
        'issues_by_severity': _group_issues_by_severity(assessment.issues or [])
    }
    
    # 构建完整报告
    from app.schemas.assessment import AssessmentDetailResponse
    report = AssessmentReport(
        assessment=AssessmentDetailResponse.model_validate(assessment),
        record=record_info,
        statistics=statistics,
        charts_data=charts_data
    )
    
    return ResponseModel(data=report)


def _get_score_grade(score: int) -> str:
    """根据分数获取等级"""
    if score >= 90:
        return "优秀"
    elif score >= 80:
        return "良好"
    elif score >= 70:
        return "中等"
    elif score >= 60:
        return "及格"
    else:
        return "不及格"


def _group_issues_by_type(issues) -> dict:
    """按问题类型分组统计"""
    type_count = {}
    for issue in issues:
        issue_type = issue.issue_type
        type_count[issue_type] = type_count.get(issue_type, 0) + 1
    
    return {
        'labels': list(type_count.keys()),
        'values': list(type_count.values())
    }


def _group_issues_by_severity(issues) -> dict:
    """按严重程度分组统计"""
    severity_count = {}
    for issue in issues:
        severity = issue.severity
        severity_count[severity] = severity_count.get(severity, 0) + 1
    
    # 确保所有严重程度都有值
    severity_order = ['critical', 'major', 'minor', 'info']
    labels = ['严重', '主要', '次要', '提示']
    values = [severity_count.get(s, 0) for s in severity_order]
    
    return {
        'labels': labels,
        'values': values
    }


@router.get("/{record_id}/export/pdf")
async def export_report_to_pdf(
    record_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    导出报告为 PDF 格式
    """
    # 获取病历
    record = await RecordCRUD.get_by_id(db, record_id)
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="病历不存在"
        )
    
    # 获取最新评估
    assessment = await AssessmentCRUD.get_by_record_id(db, record_id, latest_only=True)
    if not assessment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="该病历暂无评估记录，请先进行评估"
        )
    
    # 构建报告数据
    report_data = _build_report_data(record, assessment)
    
    try:
        # 生成 PDF
        pdf_buffer = ReportExporter.export_to_pdf(report_data)
        
        # 返回文件流 - 使用 URL 编码处理中文文件名
        filename = f"report_{record.patient_name}_{record_id}.pdf"
        encoded_filename = quote(filename)
        
        return StreamingResponse(
            pdf_buffer,
            media_type="application/pdf",
            headers={
                "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
            }
        )
    except Exception as e:
        app_logger.error(f"导出PDF失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"导出PDF失败: {str(e)}"
        )


@router.get("/{record_id}/export/excel")
async def export_report_to_excel(
    record_id: UUID,
    db: AsyncSession = Depends(get_db)
):
    """
    导出报告为 Excel 格式
    """
    # 获取病历
    record = await RecordCRUD.get_by_id(db, record_id)
    if not record:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="病历不存在"
        )
    
    # 获取最新评估
    assessment = await AssessmentCRUD.get_by_record_id(db, record_id, latest_only=True)
    if not assessment:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="该病历暂无评估记录，请先进行评估"
        )
    
    # 构建报告数据
    report_data = _build_report_data(record, assessment)
    
    try:
        # 生成 Excel
        excel_buffer = ReportExporter.export_to_excel(report_data)
        
        # 返回文件流 - 使用 URL 编码处理中文文件名
        filename = f"report_{record.patient_name}_{record_id}.xlsx"
        encoded_filename = quote(filename)
        
        return StreamingResponse(
            excel_buffer,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={
                "Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"
            }
        )
    except Exception as e:
        app_logger.error(f"导出Excel失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"导出Excel失败: {str(e)}"
        )


def _build_report_data(record, assessment) -> dict:
    """构建报告数据"""
    # 构建病历基本信息
    record_info = {
        'id': str(record.id),
        'patient_name': record.patient_name,
        'patient_age': record.patient_age,
        'patient_gender': record.patient_gender,
        'department': record.department,
        'visit_date': record.visit_date.isoformat() if record.visit_date else None,
        'chief_complaint': record.chief_complaint,
        'diagnosis': record.diagnosis,
        'doctor_name': record.doctor_name,
        'created_at': record.created_at.isoformat()
    }
    
    # 构建统计信息
    statistics = {
        'total_issues': len(assessment.issues) if assessment.issues else 0,
        'critical_issues': sum(
            1 for issue in (assessment.issues or [])
            if issue.severity == 'critical'
        ),
        'major_issues': sum(
            1 for issue in (assessment.issues or [])
            if issue.severity == 'major'
        ),
        'minor_issues': sum(
            1 for issue in (assessment.issues or [])
            if issue.severity == 'minor'
        )
    }
    
    # 构建图表数据
    charts_data = {
        'radar_chart': {
            'dimensions': ['完整性', '规范性', '一致性', '准确性'],
            'scores': [
                assessment.completeness_score,
                assessment.standardization_score,
                assessment.consistency_score,
                assessment.accuracy_score
            ],
            'max_score': 100
        },
        'bar_chart': {
            'categories': ['完整性', '规范性', '一致性', '准确性'],
            'values': [
                assessment.completeness_score,
                assessment.standardization_score,
                assessment.consistency_score,
                assessment.accuracy_score
            ]
        },
        'score_gauge': {
            'overall_score': assessment.overall_score,
            'max_score': 100,
            'grade': _get_score_grade(assessment.overall_score)
        },
        'issues_by_type': _group_issues_by_type(assessment.issues or []),
        'issues_by_severity': _group_issues_by_severity(assessment.issues or [])
    }
    
    # 转换 assessment 为字典
    from app.schemas.assessment import AssessmentDetailResponse
    assessment_dict = AssessmentDetailResponse.model_validate(assessment).model_dump()
    
    return {
        'assessment': assessment_dict,
        'record': record_info,
        'statistics': statistics,
        'charts_data': charts_data
    }

